/* Clear all existing data from memory */
clear all

/* Close any open log files and start a new log */
capture log close
log using "$logs\trend_relative_rejected.log", replace

/* Load matched sample dataset for rejected borrowers */
use "$output\rejected_psm.dta", clear

/* Sort dataset by firm ID (siren) and month-date (mdate) */
sort siren mdate

/* Restrict data to the analysis period: 2014 to 2019 */
keep if mdate < mofd(date("20200101","YMD"))
keep if mdate > mofd(date("20131231","YMD"))

/* Apply frequency weights */
keep if weight != .
su weight, d
gen max_weight = `r(max)'  /* Get the max weight for expansion */
expand max_weight  /* Expand dataset according to weight */
bys siren mdate: gen nb = _n  /* Generate a unique observation number per firm-date */
keep if nb <= weight  /* Keep observations within the assigned weight */

/*********** Trend Analysis for Rejected Borrowers *******************/

/* TREND RELATIVE Figure C1b */
preserve
keep if deltamonths >= -12  /* Keep data within -12 to +24 months from event */
keep if deltamonths <= 24

/* Compute total loan amount */
gen loan = stloan + ltloan + bm + bi + oc

/* Aggregate loan components by firm, acceptance status, and time variables */
collapse (sum) loan ltloan stloan co bm bi, by(siren accepted nb deltamonths year mdate)

/* Compute log-transformed variables */
gen lloan = log(loan)  /* Log of total loan */
gen lltloan = log(ltloan + bm + bi)  /* Log of long-term loans including leasing */
gen lstloan = log(stloan)  /* Log of short-term loans */
gen lco = log(co)  /* Log of credit lines */
gen lother = log(loan - co - ltloan - bm - bi)  /* Log of other loan components */

/* Collapse again to compute the mean by acceptance status and time */
collapse (mean) lloan lltloan lstloan lco lother, by(accepted deltamonths)

/* Generate the trend plot comparing accepted vs rejected borrowers */
foreach var in lloan {
    twoway (connected `var' deltamonths if accepted == 1, color(emerald) msize(medsmall) lpattern(shortdash) lwidth(medthick))  ///
           (connected `var' deltamonths if accepted == 0, color(gs10%80) msize(medsmall) msymbol(square) lpattern(dash) lwidth(medthick)), ///
    legend(label(1 "FinTech borrowers") label(2 "Rejected borrowers") region(color(white)) size(medlarge) position(6)///
    plotregion(color(white)) graphregion(color(white)) ///
    xlabel(-12(2)24, labsize(small)) ///
    xtitle("") ytitle("Bank credit (excluding outside loan)") ///
    xsize(6) ysize(4) ylabel(, nogrid) xline(0) yscale(range(5.3 5.6)) ylab(5.3(0.1)5.6)

    /* Save the graph */
    graph save "$figures/Figure_C1b_Trend_relative_`var'_rejected_matched.gph", replace
    graph export "$figures/Figure_C1b_Trend_relative_`var'_rejected_matched.pdf", replace
}
restore

/* Close log file */
log close
